<?php


namespace app\base\service;

use think\admin\service\AdminService;

use think\Cache;


/**
 * 蝉镜平台服务
 * Class AdminService
 * @package think\admin\service
 */
class ChanjingService extends AdminService
{



    protected $url = 'https://www.chanjing.cc/api/';
    //开发环境
    //private $callbackHost  = 'http://dev.blueant.pro/base/api.Chanjing/';
    //生产环境
    private $callbackHost  = 'http://dev.blueant.pro/base/api.Chanjing/';

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        if($BACKEND_DOMAIN = env('BACKEND_DOMAIN', '')){
            $this->callbackHost= $BACKEND_DOMAIN.'/base/api.Chanjing/';
        }
       // $callbackHost= env('DB_MYSQL_DATABASE', 'ai_redian_video').'http://dev.blueant.pro/base/api.Chanjing/';
    }

    public function getAccessToken($user_id,$flag=false)
    {
//        $api_config_type = $this->app->db->name("ai_user")->where(['id'=>$user_id])->value("api_config_type");
//        if($api_config_type==1){
//            $user_id=10000;
//        }
        $config = $this->app->db->name('ai_api_config')
            ->where(['user_id' => $user_id,'type'=>8])->find();
        if(empty($config)){
            $config = $this->app->db->name('ai_api_config')
                ->where(['user_id' => 10000,'type'=>8])->find();
            //return $this->resulet(0,'请先配置API参数');
        }
        $cache = RedisService::instance()->store();
        $appid = $config['appid'];
        if($cache->get("chanjing_token".$user_id) && !$flag){
            return $cache->get('chanjing_token'.$user_id);
        }else{
            $url = $this->url."open/v1/access_token";
            $data = [
                'app_id'=>$appid,
                'secret_key'=>$config['access_key']
            ];
            $options['headers'] = ['Content-Type: application/json'];
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);
            $this->app->log->error("getAccessToken:".json_encode($res));
            if(!$res){
                return $this->resulet(0,'请求失败');
            }
            if($res['code']==0){
                $expire_in = $res['data']['expire_in']-time()-30;
                $cache->set("chanjing_token".$user_id,$res['data']['access_token'],$expire_in);

                return  $res['data']['access_token'];
            }else{
                return $this->resulet(0,$res['msg']);
            }

        }


    }

    protected function resulet($code=0,$msg='',$data=[])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }

    //创建数字人
    public function createAvatar($user_id,$name,$material_video,$train_type)
    {
        $retryCount = 0;
        do{
            $accessToken = $this->getAccessToken($user_id);
            if(is_array($accessToken)){
                return $accessToken;
            }
            $url = $this->url."open/v1/create_customised_person";
            $data= [
                'name'=>$name,
                'material_video'=>$material_video,
                'callback'=>$this->callbackHost."createAvatarBack",
                // 'train_type'=>"figure"
            ];
            if($train_type){
                $data['train_type'] = "figure";
            }
            $options['headers'] = ['access_token:'.$accessToken,'Content-Type: application/json'];
            $options['timeout'] = 600;
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);
            $this->app->log->error("createAvatarService:".json_encode($res));
            if($res){
                if($res['code']==0){
                    return $this->resulet(1,'success',$res['data']);
                }elseif($res['code']==40001){
                    //QPS超限等待60秒
                    sleep(60);
                    $retryCount++;
                }else{
                    if($res['msg']=="AccessToken已失效"){
                        $this->getAccessToken($user_id,true);
                    }else{
                        return $this->resulet(0,$res['msg']);
                    }
                }
            }else{
                return $this->resulet(0,'请求失败');
            }
        }while($retryCount < 10);
        return $this->resulet(0,'请求失败');
    }

    //查询数字人详情
    public function getAvatarInfo($user_id,$avatar_id)
    {
        $accessToken = $this->getAccessToken($user_id);
        if(is_array($accessToken)){
            return $accessToken;
        }
        $url = $this->url."open/v1/customised_person";
        $data= [
            'id'=>$avatar_id,
        ];
        $options['headers'] = ['access_token:'.$accessToken];
        $res = http_get($url,$data,$options);
        $res = json_decode($res,true);
        $this->app->log->error("getAvatarInfoService:".json_encode($res));
        if($res){
            if($res['code']==0){
                return $this->resulet(1,'success',$res['data']);
            }else{
                return $this->resulet(0,$res['msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }
    }

    //生成口播视频
    public function createAvatarVideo($user_id,$avatar_id,$voice_url)
    {
        $retryCount = 0;
        do{
            $accessToken = $this->getAccessToken($user_id);
            if(is_array($accessToken)){
                return $accessToken;
            }
            $url = $this->url."open/v1/create_video";
            $data = [
                'person'=>[
                    'id'=>$avatar_id,
                    'x'=>0,
                    'y'=>0,
                    'width'=>1080,
                    'height'=>1920,
                    //  'figure_type'=>"sit_body"
                ],
                'audio'=>[
                    'wav_url'=>$voice_url,
                    'type'=>"audio",
                    'volume'=>100,
                ],
                'callback'=>$this->callbackHost."createAvatarVideoBack",
            ];
            $options['headers'] = ['access_token:'.$accessToken];
            $options['timeout'] = 600;
            $res = http_post($url,json_encode($data),$options);
            $this->app->log->error("蝉镜生成口播视频:".json_encode($data).json_encode($options));
            $res = json_decode($res,true);
            $this->app->log->error("createAvatarVideo:".json_encode($res));
            if($res){
                if($res['code']==0){
                    return $this->resulet(1,'success',$res['data']);
                }elseif($res['code']==40001){
                    //QPS超限等待60秒
                    $this->app->log->error("QPS超限等待60秒");
                    sleep(60);
                    $retryCount++;
                }else{
                    if($res['msg']=="AccessToken已失效"){
                        $this->getAccessToken($user_id,true);
                    }else{
                        return $this->resulet(0,$res['msg']);
                    }
                }
            }else{
                return $this->resulet(0,'请求失败');
            }
        }while($retryCount < 10);

        return $this->resulet(0,'请求失败');

    }


    //生成口播视频(文本)
    public function createAvatarVideoByText($user_id,$avatar_id,$text,$audio_man)
    {
        $retryCount = 0;
        do{
            $accessToken = $this->getAccessToken($user_id);
            if(is_array($accessToken)){
                return $accessToken;
            }
            $url = $this->url."open/v1/create_video";
            $data = [
                'person'=>[
                    'id'=>$avatar_id,
                    'x'=>0,
                    'y'=>0,
                    'width'=>1080,
                    'height'=>1920,
                    //  'figure_type'=>"sit_body"
                ],
                'audio'=>[
                    'tts'=>[
                        'text'=>[$text],
                        'speed'=>0.9,
                        'audio_man'=>$audio_man
                    ],
                    "wav_url"=>"",
                    'type'=>"tts",
                    'volume'=>100,
                ],
                'screen_width'=>1080,
                'screen_height'=>1920,
                'callback'=>$this->callbackHost."createAvatarVideoBack",
            ];
          //  return $data;
            $options['headers'] = ['access_token:'.$accessToken];
            $options['timeout'] = 600;
            $res = http_post($url,json_encode($data),$options);
            $this->app->log->error("蝉镜生成口播视频:".json_encode($data).json_encode($options));
            $res = json_decode($res,true);
            $this->app->log->error("createAvatarVideo:".json_encode($res));
            if($res){
                if($res['code']==0){
                    return $this->resulet(1,'success',$res['data']);
                }elseif($res['code']==40001){
                    //QPS超限等待60秒
                    $this->app->log->error("QPS超限等待60秒");
                    sleep(60);
                    $retryCount++;
                }else{
                    if($res['msg']=="AccessToken已失效"){
                        $this->getAccessToken($user_id,true);
                    }else{
                        return $this->resulet(0,$res['msg']);
                    }
                }
            }else{
                return $this->resulet(0,'请求失败');
            }
        }while($retryCount < 10);


        return $this->resulet(0,'请求失败');
    }

    //查询口播人详情
    public function getAvatarVideoInfo($user_id,$video_id)
    {
        $accessToken = $this->getAccessToken($user_id);
        if(is_array($accessToken)){
            return $accessToken;
        }
        $url = $this->url."open/v1/video";
        $data= [
            'id'=>$video_id,
        ];
        $options['headers'] = ['access_token:'.$accessToken];
        $res = http_get($url,$data,$options);
        $res = json_decode($res,true);
        $this->app->log->error("getAvatarVideoInfo:".json_encode($res));
        if($res){
            if($res['code']==0){
                return $this->resulet(1,'success',$res['data']);
            }else{
                return $this->resulet(0,$res['msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }
    }

    //创建声音
    public function createVoice($user_id,$voice_name,$voice_url,$model_type="cicada1.0")
    {
        $retryCount = 0;
        do{
            $accessToken = $this->getAccessToken($user_id);
            if(is_array($accessToken)){
                return $accessToken;
            }
            if(empty($model_type)){
                $model_type = "cicada1.0";
            }
            $url = $this->url."open/v1/create_customised_audio";
            $data= [
                'name'=>$voice_name,
                'url'=>$voice_url,
                'callback'=>$this->callbackHost."createVoiceBack",
                "model_type"=>$model_type,
                "text"=>"你好,我是你的蓝蚁智控数字人"
            ];

            //  dump($data);
            $options['headers'] = ['access_token:'.$accessToken,'Content-Type: application/json'];
            $options['timeout'] = 600;
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);
            $this->app->log->error("createVoice:".json_encode($res));
            if($res){
                if($res['code']==0){
                    return $this->resulet(1,'success',$res['data']);
                }elseif($res['code']==40001){
                    //QPS超限等待60秒
                    sleep(60);
                    $retryCount++;
                }else{
                    if($res['msg']=="AccessToken已失效"){
                         $this->getAccessToken($user_id,true);
                    }else{
                        return $this->resulet(0,$res['msg']);
                    }

                }
            }else{
                return $this->resulet(0,'请求失败');
            }
        }while($retryCount < 10);

        return $this->resulet(0,'请求失败');
    }

    //查询声音详情
    public function getVoiceInfo($user_id,$voice_id)
    {
        $accessToken = $this->getAccessToken($user_id);
        if(is_array($accessToken)){
            return $accessToken;
        }
        $url = $this->url."open/v1/customised_audio";
        $data= [
            'id'=>$voice_id,
        ];
        $options['headers'] = ['access_token:'.$accessToken];
        $res = http_get($url,$data,$options);
        $res = json_decode($res,true);
        $this->app->log->error("getVoiceInfo:".json_encode($res));
        if($res){
            if($res['code']==0){
                return $this->resulet(1,'success',$res['data']);
            }else{
                return $this->resulet(0,$res['msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }
    }

    //创建音频
    public function createAudio($user_id,$audio_id,$text)
    {
        $retryCount = 0;
        do{
            $accessToken = $this->getAccessToken($user_id);
            if(is_array($accessToken)){
                return $accessToken;
            }
            $url = $this->url."open/v1/create_audio_task";
            $data= [
                'audio_man'=>$audio_id,
                'text'=>[
                    'text'=>$text,
                ],
                'speed'=>1.1,
                'pitch'=>1,
                'volume'=>1,
                'callback'=>$this->callbackHost."createAudioBack",
            ];
            $options['headers'] = ['access_token:'.$accessToken,'Content-Type: application/json'];
            $options['timeout'] = 600;
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);
            $this->app->log->error("createVoice:".json_encode($res));
            if($res){
                if($res['code']==0){
                    return $this->resulet(1,'success',$res['data']['task_id']);
                }elseif($res['code']==40001){
                    //QPS超限等待60秒
                    sleep(60);
                    $retryCount++;
                }else{
                    if($res['msg']=="AccessToken已失效"){
                        $this->getAccessToken($user_id,true);
                    }else{
                        return $this->resulet(0,$res['msg']);
                    }
                }
            }else{
                return $this->resulet(0,'请求失败');
            }
        }while($retryCount < 10);
        return $this->resulet(0,'请求失败');
    }

    //拉取数字人列表
    public function getAvatarList($user_id){
        $accessToken = $this->getAccessToken($user_id);
        if(is_array($accessToken)){
            return $accessToken;
        }
        $url = $this->url."open/v1/list_customised_audio";
        $data= [
            'page'=>1,
            'page_size'=>20,
        ];
        $options['headers'] = ['access_token:'.$accessToken,'Content-Type: application/json'];
        $res = http_post($url,json_encode($data),$options);
        $res = json_decode($res,true);
        dump($res);
        if($res){
            if($res['code']==0){
                return $this->resulet(1,'success',$res['data']);
            }else{
                return $this->resulet(0,$res['msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }
    }


}
